<template>
  <div class="groupOperate">
    <div class="header">
      <div class="header-l">
        <div class="block" v-if="rootNameStatus == 'default'">
          <span class="groupName" :title="groupName">{{ groupName }}</span>
          <icon-font
            type="ic-edit"
            class="editIcon"
            @click="editRootName"
            v-if="isRoot"
          ></icon-font>
        </div>
        <div class="block" v-else>
          <a-space>
            <a-tooltip placement="top" :visible="curRootVisible">
              <template slot="title">
                <span>{{ curRootErrorTootip }}</span>
              </template>
              <a-input
                v-model="curRootName"
                :class="{ formatError: curRootVisible }"
              />
            </a-tooltip>
            <a-icon
              type="close-circle"
              class="editOperateIcon"
              @click="cancelRootEdit"
            />
            <a-icon
              type="check-circle"
              class="editOperateIcon"
              @click="saveRootEdit"
            />
          </a-space>
        </div>
      </div>
      <div class="header-r">
        <a-space>
          <a-button v-if="hasAddLocationBtn" @click="addLocationGroup">{{
            $t('groupOperate.addmanner')
          }}</a-button>
          <a-button v-if="hasShareNetBtn" @click="shareGroup">{{
            $t('groupOperate.shareother')
          }}</a-button>
          <a-button v-if="hasHandOverBtn" @click="handOverGroup">{{
            $t('groupOperate.movenet')
          }}</a-button>
          <a-button v-if="hasAddBuildingBtn" @click="addNetWork">{{
            $t('groupOperate.addnet')
          }}</a-button>
          <a-dropdown v-if="hasMoreOperateBtn">
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="edit">{{
                $t('groupOperate.editmannergroup')
              }}</a-menu-item>
              <a-menu-item key="delete">{{
                $t('groupOperate.deletmannergroup')
              }}</a-menu-item>
            </a-menu>
            <a-button
              >{{ $t('groupOperate.moreaction') }}<a-icon type="down"
            /></a-button>
          </a-dropdown>
        </a-space>
      </div>
    </div>
    <div class="content" v-if="!loadType" @scroll="handelscroll">
      <div class="manageUser listBox">
        <a-space class="boxTitle">
          {{ $t('groupOperate.manner') }}（{{ manageUserList.length }}）
          <a-icon type="plus-circle" class="addIcon" @click="addManageUser" />
        </a-space>
        <div class="boxContent">
          <ul class="manageUserList">
            <li
              class="manageUserLi"
              v-for="item in manageUserList"
              :key="item.userId"
            >
              <span class="accountName" :title="item.userName">{{
                item.userName
              }}</span>
              <a-select
                class="selectAuthority"
                @change="
                  (value) => {
                    userAuthority(value, item.userId);
                  }
                "
                :value="`${item.operation}`"
                style="width: 200px"
              >
                <a-select-option value="3">
                  {{ $t('groupOperate.missionedit') }}
                </a-select-option>
                <a-select-option value="1">
                  {{ $t('groupOperate.notmissionedit') }}
                </a-select-option>
              </a-select>
              <icon-font
                type="ic-delete"
                class="delIcon"
                @click="deleteManageUser(item)"
              />
            </li>
          </ul>
        </div>
      </div>
      <div class="subGroup listBox">
        <a-space class="boxTitle">
          {{
            ['LOCATION', 'ROOT'].indexOf(groupInfo.type) != -1
              ? $t('groupOperate.mannerandnet')
              : $t('groupOperate.devicegroup')
          }}（{{ subGroupList.length }}）
          <a-icon
            type="plus-circle"
            class="addIcon"
            v-if="groupInfo.type == 'BUILDING'"
            @click="addDeviceGroup"
          />
        </a-space>
        <div class="boxContent">
          <ul class="subGroupList">
            <li v-for="item in showSubGroupList" :key="item.groupId">
              <div class="block" v-if="item.groupId != editSubGroupId">
                <span
                  class="groupName"
                  :title="item.name"
                  style="width: 200px; font-weight: normal; font-size: 14px"
                >
                  <icon-font
                    v-if="['ROOT', 'LOCATION'].indexOf(item.type) != -1"
                    type="ic-tree-group"
                  />
                  <icon-font
                    v-else-if="item.type == 'BUILDING'"
                    type="ic-tree-network"
                  />
                  <icon-font v-else type="ic-tree-device" />
                  {{ item.name }}
                </span>
                <icon-font
                  type="ic-edit"
                  style="margin-left: 30px; font-size: 20px; cursor: pointer"
                  @click="subgEdit(item)"
                />
                <icon-font
                  type="ic-delete"
                  style="margin-left: 10px; font-size: 16px; cursor: pointer"
                  @click="subgDel(item)"
                />
              </div>
              <div class="block" v-else>
                <a-tooltip placement="top" :visible="subGroupVisible">
                  <template slot="title">
                    <span>{{ subGroupErrorTootip }}</span>
                  </template>
                  <a-input
                    v-model="subGroupName"
                    :class="{ formatError: subGroupVisible }"
                    style="width: 200px"
                  />
                </a-tooltip>
                <a-icon
                  type="close-circle"
                  class="editOperateIcon"
                  @click="cancelSubGEdit"
                  style="margin-left: 30px"
                />
                <a-icon
                  type="check-circle"
                  class="editOperateIcon"
                  @click="saveSubGEdit(item)"
                  style="margin-left: 10px"
                />
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <OperateGroup
      v-if="loadType == 'addLocation'"
      :groupInfo="groupInfo"
      @closeCallback="closeAddLocationCallback"
      :operateType="operateType"
    />
    <!-- 添加设备组弹窗 -->
    <AddDeviceGroup
      v-if="showAddSubGroup"
      :parentGroup="groupInfo.groupId"
      @closeCallback="closeAddDevGroupCallback"
    />
    <!-- 添加管理员弹窗 -->
    <AddManageUser
      v-if="showAddManageUser"
      :groupId="groupInfo.groupId"
      :alreadyUserList="manageUserList"
      @closeCallback="closeAddUserCallBack"
    />
    <!-- 分享网络弹窗 -->
    <ShareGroup
      v-if="showShareGroup"
      :groupInfo="groupInfo"
      @closeCallback="closeShareGCallBack"
    />
    <HandoverGroup
      v-if="showHandoverGroup"
      :groupInfo="groupInfo"
      @closeCallback="closeHandGCallBack"
    />
  </div>
</template>

<script>
import { requestHttp, maccApi, ValiDateTools } from '@utils/index';
import { mapState } from 'vuex';
import { RjModal } from '@components';
import AddDeviceGroup from '../addDeviceGroup/index.vue';
import AddManageUser from '../addManageUser/index.vue';
import ShareGroup from '../shareGroup/index.vue';
import HandoverGroup from '../handoverGroup/index.vue';
import OperateGroup from '../operateGroup/index.vue';
import { i18nRender } from '@/locales';
export default {
  name: 'GroupOperate',
  props: {
    groupInfo: {
      type: Object,
    },
  },
  components: {
    AddDeviceGroup,
    AddManageUser,
    ShareGroup,
    // ShareUrl,
    HandoverGroup,
    OperateGroup,
  },
  data() {
    return {
      rootNameForm: {
        name: '',
      },
      rootNameStatus: 'default', //default:隐藏编辑框，edit:显示编辑框
      curRootName: '',
      curRootVisible: false,
      curRootErrorTootip: '',
      manageUserList: [],
      subGroupList: [],
      editSubGroupId: null,
      subGroupVisible: false,
      subGroupErrorTootip: '',
      subGroupName: '',
      showAddSubGroup: false,
      showAddManageUser: false,
      showShareGroup: false,
      showShareUrl: false,
      showHandoverGroup: false,
      operation: null,
      expiredAt: null,
      loadType: null,
      showSubGroupList: [],
      showSubGroup: {
        start: 0,
        size: 50,
      },
    };
  },
  mounted() {},
  computed: {
    ...mapState('User', ['userInfo']),
    groupName() {
      return this.groupInfo.name;
    },
    //是否显示“添加管理子分组”按钮
    hasAddLocationBtn() {
      // return this.groupInfo.type == 'LOCATION';
      return ['ROOT', 'LOCATION'].indexOf(this.groupInfo.type) != -1;
    },
    //是否显示“移交网络"按钮
    hasHandOverBtn() {
      return ['LOCATION', 'BUILDING'].indexOf(this.groupInfo.type) != -1;
    },
    //是否显示“添加网络”按钮
    hasAddBuildingBtn() {
      return ['ROOT', 'LOCATION'].indexOf(this.groupInfo.type) != -1;
    },
    //是否显示“分享给他人”按钮
    hasShareNetBtn() {
      return this.groupInfo.type == 'BUILDING';
    },
    //是否显示”更多操作“按钮
    hasMoreOperateBtn() {
      return this.groupInfo.type != 'ROOT';
    },
    //是否是根分组
    isRoot() {
      return this.groupInfo.type == 'ROOT';
    },
    //是否VIP
    isVip() {
      const userLabel =
        this.$store.state.User?.userInfo?.label?.split(';') ?? [];
      return userLabel.includes('Vip');
    },
  },
  watch: {
    groupInfo: {
      handler: function (val) {
        this.resetStatus();
        this.getGroupManageUser(); //获取分组管理员
        this.getSubGroup(); //获取子分组
      },
      immediate: true,
    },
  },
  methods: {
    //点击编辑根分组名称
    editRootName() {
      this.curRootName = this.groupName;
      this.rootNameStatus = 'edit';
    },
    //取消根分组编辑
    cancelRootEdit() {
      this.rootNameStatus = 'default';
      // this.resetStatus();
      this.curRootVisible = false;
      this.curRootErrorTootip = '';
    },
    //保存根分组编辑
    async saveRootEdit() {
      const checkRes = this.checkRootGroupName();
      if (!checkRes) {
        this.curRootVisible = true;
        return;
      }
      const { groupId } = this.groupInfo;
      let url = `${maccApi.EDIT_GROUP_ROOT_NAME_API.replace(
        '{groupId}',
        groupId
      )}`;
      const { code, msg } = await requestHttp({
        api: url,
        method: 'PUT',
        params: {},
        querys: {
          name: this.curRootName,
        },
      });
      if (code == 0) {
        this.rootNameStatus = 'default';
        this.$store.dispatch('Group/getGroupTree');
      } else {
        this.$message.error(msg || this.$t('groupOperate.changeparentsfail'));
      }
    },
    //删除管理员
    deleteManageUser(info) {
      const that = this;
      RjModal.confirm({
        title: this.$t('businessNet.tips'),
        content: this.$t('groupOperate.suredeletadmin'),
        async onOk() {
          const { userId } = info;
          const { groupId } = that.groupInfo;
          const { code, msg } = await requestHttp({
            api: `${maccApi.ADD_GROUP_USER_API}?user_id=${userId}&group_id=${groupId}`,
            method: 'DELETE',
          });
          if (code == 0) {
            that.getGroupManageUser();
          } else {
            that.$message.error(msg || this.$t('groupOperate.suredeletfail'));
          }
        },
      });
    },
    //点击“分享给他人”
    shareGroup() {
      this.showShareGroup = true;
    },
    //点击“移交网络”
    handOverGroup() {
      this.showHandoverGroup = true;
    },
    //点击“编辑网络”
    editGroup() {
      this.operateType = 'edit';
      this.loadType = 'addLocation';
    },
    //点击“删除网络”
    delGroup() {
      // RjModal.confirm({
      //   title:'提示',
      //   content:'确认删除该分组么？',
      //   async onOk(){
      //   }
      // })
      this.subgDel(this.groupInfo);
    },
    resetStatus() {
      this.rootNameStatus = 'default';
      this.curRootVisible = false;
      this.curRootErrorTootip = '';
      this.manageUserList = [];
      this.subGroupList = [];
      this.editSubGroupId = null;
      this.subGroupVisible = false;
      this.subGroupErrorTootip = '';
      this.subGroupName = '';
      this.loadType = null;
    },
    //点击“添加管理子分组”
    addLocationGroup() {
      this.operateType = 'add';
      // this.netType = 'LOCATION';
      this.loadType = 'addLocation';
    },
    //校验分组名称
    checkRootGroupName() {
      if (!/^[\w\u4e00-\u9fa5-]{1,32}$/.test(this.curRootName)) {
        this.curRootErrorTootip = this.$t('groupOperate.error3');
        return false;
      } else if (this.curRootName.toUpperCase() == 'ROOT') {
        this.curRootErrorTootip = this.$t('groupOperate.parentroot');
        return false;
      }
      return true;
    },
    //点击“添加网络”
    addNetWork() {
      console.log('this.groupInfo', this.groupInfo);
      const { groupId } = this.groupInfo;
      console.log('groupId', groupId);
      if (window === window.top) {
        console.log('window.top');
        this.$EventBus.$emit('Add_NETWORK', {
          pGroupId: groupId,
        });
      } else {
        console.log('没有window.top');
        this.$iframeMsg('Add_NETWORK', {
          pGroupId: groupId,
        });
      }
    },
    handleMenuClick({ key }) {
      switch (key) {
        case 'edit':
          // console.log(key);
          this.editGroup();
          break;
        case 'delete':
          // console.log(key);
          this.delGroup();
          break;
        default:
          break;
      }
    },
    //添加设备组
    addDeviceGroup() {
      this.showAddSubGroup = true;
    },
    //关闭添加管理子分组
    closeAddLocationCallback(result) {
      if (result && result.success) {
        this.$store.dispatch('Group/updataGroupTree');
      }
      this.loadType = null;
    },
    //关闭设备组添加弹窗
    closeAddDevGroupCallback(result) {
      if (result && result.success) {
        this.$store.dispatch('Group/updataGroupTree');
      }
      this.showAddSubGroup = false;
    },
    //添加分组管理员
    addManageUser() {
      this.showAddManageUser = true;
    },
    //关闭添加分组管理员弹窗
    closeAddUserCallBack() {
      this.getGroupManageUser();
      this.showAddManageUser = false;
    },
    //关闭分享网络弹窗
    closeShareGCallBack() {
      this.showShareGroup = false;
      // this.$nextTick(() => {
      //   if (params) {
      //     this.showShareUrl = true;
      //     this.operation = params.operation;
      //     this.expiredAt = params.expiredAt;
      //   }
      // });
    },
    // //关闭分享链接弹窗
    // closeShareUrlCallBack() {
    //   this.showShareUrl = false;
    // },
    //关闭网络移交弹窗
    closeHandGCallBack(result) {
      if (result && result.success) {
        this.$store.dispatch('Group/getGroupTree');
      }
      this.showHandoverGroup = false;
    },
    //修改用户权限
    userAuthority(value, userId) {
      const that = this;
      const { groupId } = this.groupInfo;
      RjModal.confirm({
        title: i18nRender('businessNet.tips'),
        content: i18nRender('groupOperate.surechangeuser'),
        async onOk() {
          console.log(value);
          let { code, msg } = await requestHttp({
            api: `${maccApi.SET_GROUP_MANAGE_USER_AUTH_API}`,
            method: 'POST',
            params: {
              userId: userId,
              groupId: groupId,
              operation: parseInt(value),
            },
          });
          if (code == 0) {
            that.getGroupManageUser();
          } else {
            that.$message.error(msg || this.$t('groupOperate.changeuserfail'));
          }
        },
      });
    },
    //点击删除分组
    subgDel(info) {
      const { groupId, name } = info;
      const that = this;
      RjModal.confirm({
        title: i18nRender('businessNet.tips'),
        content: this.$t('groupOperate.consumdelet', [name]),
        async onOk() {
          const { code, msg } = await requestHttp({
            api: `${maccApi.NETWORK_DEL_API.replace('{groupId}', groupId)}`,
            method: 'DELETE',
          });
          if (code == 0) {
            that.$store.dispatch('Group/getGroupTree');
          } else {
            that.$message.error(msg || this.$t('groupOperate.deletgroupfail'));
          }
        },
      });
    },
    //点击编辑子分组
    subgEdit(groupInfo) {
      const { groupId, name } = groupInfo;
      this.subGroupName = name;
      this.editSubGroupId = groupId;
      this.subGroupVisible = false;
      this.subGroupErrorTootip = '';
    },
    //取消编辑子分组
    cancelSubGEdit() {
      this.editSubGroupId = null;
      this.subGroupVisible = false;
      this.subGroupErrorTootip = '';
    },
    //保存编辑组分组
    async saveSubGEdit(info) {
      const checkRes = ValiDateTools.checkGroupName(
        this.subGroupName,
        this.isVip
      );
      const { result, msg: checkMsg } = checkRes;
      if (!result) {
        this.subGroupVisible = true;
        this.subGroupErrorTootip = checkMsg;
        return;
      }
      const { groupId } = info;
      const { code, msg } = await requestHttp({
        api: `${maccApi.UPDATE_GROUP_API.replace('{groupId}', groupId)}`,
        method: 'PUT',
        params: {
          name: this.subGroupName,
        },
      });
      if (code == 0) {
        this.$store.dispatch('Group/getGroupTree');
      } else {
        this.$message.error(msg || this.$t('groupOperate.changegroupfail'));
      }
    },
    //获取分组下的管理员
    async getGroupManageUser() {
      const { accountId } = this.userInfo;
      const { groupId } = this.groupInfo;
      let { code, managers, msg } = await requestHttp({
        api: `${maccApi.GET_GROUP_MANAGE_USER_API}`.replace(
          '{groupId}',
          groupId
        ),
        method: 'GET',
      });
      if (code == 0) {
        managers = managers.filter(function (item) {
          //过滤掉自己和租户管理员
          return item.userId != accountId && item.roleCode != 'TENANT_MANAGER';
        });
        this.manageUserList = managers;
      } else {
        this.$message.error(msg || this.$t('groupOperate.getmannergefail'));
      }
    },
    //获取指定分组下的子分组
    async getSubGroup() {
      const { groupId, type } = this.groupInfo;
      const depth =
        ['ROOT', 'LOCATION'].indexOf(type) != -1 ? 'BUILDING' : 'DEVICE';
      const url = `${maccApi.GET_SUB_GROUP_DATA_API}?group_id=${groupId}&depth=${depth}`;
      let { code, msg, groups } = await requestHttp({
        api: url,
        method: 'GET',
      });
      if (code == 0) {
        this.subGroupList = groups.subGroups[0].subGroups || [];
        this.showSubGroupList = [];
        this.showSubGroup.start = 0;
        this.showSubGroupList = this.subGroupList.slice(
          this.showSubGroup.start,
          this.showSubGroup.start + this.showSubGroup.size
        );
        this.showSubGroup.start =
          this.showSubGroup.start + this.showSubGroup.size;
      } else {
        this.$message.error(msg || this.$t('groupOperate.getgroupfail'));
      }
      console.log(groups);
    },
    handelscroll(e) {
      const ele = e.target;
      if (ele.clientHeight + ele.scrollTop === ele.scrollHeight) {
        console.log('到底了');
        if (this.showSubGroup.start >= this.subGroupList.length) {
          return;
        }
        this.$set(
          this,
          'showSubGroupList',
          this.showSubGroupList.concat(
            this.subGroupList.slice(
              this.showSubGroup.start,
              this.showSubGroup.start + this.showSubGroup.size
            )
          )
        );

        this.showSubGroup.start =
          this.showSubGroup.start + this.showSubGroup.size;
      }
      console.log(e.target.scrollTop, e.target.scrollTop);
    },
  },
};
</script>

<style lang="less" scoped>
.groupOperate {
  border: 1px solid #e4e4e4;
  height: 100%;
  width: 100%;
  padding: 3px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e4e4e4;
    height: 55px;
    padding: 0 10px;
    /deep/ .ant-form-explain {
      position: absolute;
      top: 100%;
    }
    .block {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      // /deep/ .ant-space-item {
      //   margin-right: 0;
      // }
    }
  }
  .content {
    flex: 1;
    padding: 10px;
    overflow: auto;
    // background: RED;
    .boxTitle {
      padding: 0 8px;
      background-color: #efefef;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .boxContent {
      padding: 8px 0;
      .manageUserList {
        .manageUserLi {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          margin-bottom: 5px;
          .accountName {
            margin-right: 10px;
            width: 180px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap; //表示强制换行显示
            display: inline-block;
          }
          .selectAuthority {
            margin-right: 10px;
          }
        }
      }
    }
  }
  .editIcon {
    margin-left: 10px;
    font-size: 20px;
    cursor: pointer;
  }
  .delIcon {
    cursor: pointer;
  }
  .editOperateIcon {
    cursor: pointer;
    font-size: 20px;
  }
  .formatError {
    border-color: red;
  }
  .addIcon {
    cursor: pointer;
    color: #666;
  }
  .groupName {
    font-size: 16px;
    font-weight: bold;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap; //表示强制换行显示
    display: inline-block;
  }
}
.ant-btn {
  border: 1px solid #2b6afd;
  background: #fff;
  color: #2b6afd;
}
.ant-btn:hover {
  background: #497ffd;
  color: #fff;
}
.subGroupList {
  max-height: 500px;
}
</style>
